import React from "react";
import Confirm from '../../../common/Confirm'
import Select_common from '../../../common/Select'
import {Modal,message,Select,Button,Input,Icon} from 'antd';
const { Option, OptGroup } = Select;
import InputBox from '../../../common/InputBox'
import PackTradeApply from './PackTradeApply'
import Relay from "react-relay";
import SaveOthersMutation from "./mutation/SaveOthersMutation";
import FindAllTemplateMutation from "./mutation/FindAllTemplateMutation";
import FindTemplateByIdMutation from "./mutation/FindTemplateByIdMutation";
import DelTemplateByIdMutation from "./mutation/DelTemplateByIdMutation";
import BatchHint from "./BatchHint";
import ReactKey from "../../../util/ReactKey"
import Util from "../../../util/Util"
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation"
import '../css/IndentManage.css'
import "./css/create_order_three.css"

export default class CreatOrderThree extends React.Component{
    constructor(props){
        super(props);
        this.state={
            textNum_r:"",
            orderTemplates:[],
            saveModalFlag:false,
            templateId:"",
            defaultValue:"请选择模板",
            templateName:"",
            remarkinput:"",
            oders:[],
            partAordlist:[],
            enterpriseList:[],
            linkman:[],
            instructions:[],
            fristchose:"",
            traderName:"",
            traderUser:"",
            traderId:"",
            dataSource_require:[
                {type:"quality",title:"质量要求",content:""},
                {type:"package",title:"包装要求",content:""},
                {type:"logistics",title:"物流要求",content:""},
                {type:"payMode",title:"付款方式",content:""},
                {type:"dutyBreak",title:"违约责任",content:""},
                {type:"checkAsk",title:"验收要求",content:""},
                ],
        };
        this.dataSource_require = [
            {type:"quality",title:"质量要求",content:""},
            {type:"package",title:"包装要求",content:""},
            {type:"logistics",title:"物流要求",content:""},
            {type:"payMode",title:"付款方式",content:""},
            {type:"dutyBreak",title:"违约责任",content:""},
            {type:"checkAsk",title:"验收要求",content:""},
        ];
        this.saveFlag = true;
        this.delFlag = true;
        this.instructions=[];
        this.odersobj={};
        this.fristchose = '';
        this.enterpriseList = [{text:"请选择客户",value:"0"}]
        this.enterprisedeobj={};
        this.linkman = [{text:'请选择联系人',value:'0'}];
        this.serviceType = sessionStorage.getItem('serviceType');
        this.userId = sessionStorage.getItem('uid');
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.messageFlag=true;

    }

    componentWillMount(){
        /*附件赋值*/
        if(this.props.fromEdit== "edit"||this.props.fromEdit == "modify"){
            this.setState({
                instructions:this.props.instructions||[],
                traderName:this.props.traderName||"",
                traderUser:this.props.traderUser||"",
                traderId:this.props.traderId||"",
                dataSource_require:this.props.dataSource_require||this.dataSource_require,
            });
            this.instructions = this.props.instructions||[]
        }

        this.ispartA = this.props.ispartA;
        Relay.Store.commitUpdate(
            new FindAllTemplateMutation({
                enterpriseId:this.enterpriseId,
                userId:this.userId,
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.findAllTemplate.findAllTemplate.errorCode;
                    if(errorCode==0){
                        let orderTemplates = response.findAllTemplate.findAllTemplate.orderTemplates;
                        let partAordlist = [];
                        this.setState({
                            orderTemplates:orderTemplates,
                        },()=>{

                        });
                    }
                }
            }
        )
    }
    componentDidMount(){
        /*备注赋值*/
        if(this.props.fromEdit== "edit"||this.props.fromEdit == "modify"){
            /*this.refs.remarkinput.setState({
                text:this.props.rmark||''
            });*/
            this.setState({
                remarkinput:this.props.rmark||'',
                textNum_r:this.props.rmark?this.props.rmark.length:0,
            })
        }
    }
    /*附件*/
    attach(){
        return  this.state.instructions.map((item,index)=>{
            return(
                <PackTradeApply  key={ReactKey.key} item={item} delqiniufile={this.delqiniufile.bind(this)}/>
            );

        })
    }
    /*添加附件*/
    addinstructions(){
        this.props.addinstructions();
    }
    addpact(name,hash,url,fileKey,sid){
        this.instructions.push({"name":name,"hash":hash,"url":url,"fileKey":fileKey,"sid":sid});
        this.setState({
            instructions:this.instructions
        });
    }
    /*删除七牛*/
    delqiniufile(item,fileKye){
        Relay.Store.commitUpdate(
            new DelQiniuFileMutation({
                fileKey : fileKye
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                    if(errorCode==0){
                        Util.removedarrayitem(this.instructions,item);
                        this.setState({
                            instructions:this.instructions
                        });
                    }
                }
            }
        )
    }

    /*选择模板*/
    handleChange(value) {
        this.setState({
            templateId:value,
        });
        Relay.Store.commitUpdate(
            new FindTemplateByIdMutation({
                templateId:value,
            }),
            {
                onFailure: () => {

                },
                onSuccess: (response) => {
                    let errorCode = response.findTemplateById.findTemplateById.errorCode;
                    if(errorCode==0){
                        let orderTemplate = response.findTemplateById.findTemplateById.orderTemplate;
                        let tid = response.findTemplateById.findTemplateById.orderTemplate.tid;
                        let dataSource_require = this.state.dataSource_require;
                        dataSource_require[0].content = orderTemplate.qualityAsk;
                        dataSource_require[1].content = orderTemplate.packageAsk;
                        dataSource_require[2].content = orderTemplate.logisticsAsk;
                        dataSource_require[3].content = orderTemplate.payMode;
                        dataSource_require[4].content = orderTemplate.dutyBreak;
                        dataSource_require[5].content = orderTemplate.checkAsk;
                        this.setState({
                            dataSource_require:dataSource_require,
                            defaultValue:tid,
                        },()=>{

                        });
                    }
                }
            }
        )
    }
    /*点击保存*/
    saveTemplate(){
        // let {dataSource_require} = this.state;
        let dataSource_require = JSON.parse(JSON.stringify(this.state.dataSource_require));
        let req = /^\s*$/g;
        let emptyFlag = false,
            empty = true;

        dataSource_require.map((item,index)=>{
            empty = item.content==null||item.content==""||item.content==undefined||req.test(item.content);
            /*六个不能同时为空，有一个有值就可以 empty-false*/
            if(!empty){
                /*有值*/
                emptyFlag=true;
                return;
            }
        });
        if(emptyFlag){
            this.setState({
                saveModalFlag:true,
                templateName:"",
            });
        }else {
            let this_ = this;
            Util.messageHint(this_,"error","没有可保存的内容");
        }
    }
    /*保存模板*/
    onSure(){
        let templateName = this.state.templateName;
        templateName=templateName.replace(/(^\s*)|(\s*$)/g,"");
        let reg = /^\s*$/g;
        if(!templateName || reg.test(templateName)){
            message.warning("模板名称不能为空！");
            return
        }
        if(this.saveFlag){
            this.saveFlag = false;
            let {dataSource_require} = this.state;
            Relay.Store.commitUpdate(
                new SaveOthersMutation({
                    qualityAsk:dataSource_require[0].content,
                    packageAsk:dataSource_require[1].content,
                    logisticsAsk:dataSource_require[2].content,
                    payMode:dataSource_require[3].content,
                    dutyBreak:dataSource_require[4].content,
                    checkAsk:dataSource_require[5].content,
                    templateName:templateName,
                    userId:this.userId,
                    enterpriseId:this.enterpriseId,
                }),
                {
                    onFailure: () => {

                    },
                    onSuccess: (response) => {
                        let errorCode = response.saveOthers.saveOthers.errorCode;
                        let value = response.saveOthers.saveOthers.value;
                        if(errorCode==0){
                            let orderTemplates = response.saveOthers.saveOthers.orderTemplates;
                            let orderTemplate = response.saveOthers.saveOthers.orderTemplate;
                            let tid = response.saveOthers.saveOthers.orderTemplate.tid;
                            let dataSource_require = this.state.dataSource_require;
                            dataSource_require[0].content = orderTemplate.qualityAsk;
                            dataSource_require[1].content = orderTemplate.packageAsk;
                            dataSource_require[2].content = orderTemplate.logisticsAsk;
                            dataSource_require[3].content = orderTemplate.payMode;
                            dataSource_require[4].content = orderTemplate.dutyBreak;
                            dataSource_require[5].content = orderTemplate.checkAsk;
                            this.setState({
                                saveModalFlag:false,
                                orderTemplates:orderTemplates,
                                dataSource_require:dataSource_require,
                                defaultValue:tid,
                                templateId:tid,
                            },()=>{
                                this.saveFlag = true;
                                message.info("保存成功")
                            });
                        }else {
                            this.saveFlag = true;
                            let this_ = this;
                            Util.messageHint(this_,"info",value);
                        }
                    }
                }
            )
        }
    }
    handleCancel = () => {
        this.setState({
            saveModalFlag: false,
        });
    };
    chooseTemplateName(e){
        let value = e.target.value;
        //提示+定时器
        let messageHint = (hintText)=>{
            hintText = hintText?hintText:"";
            if (this.messageFlag) {
                this.messageFlag = false;
                message.info(hintText);
                clearTimeout(this.messageTime);
                this.messageTime = setTimeout(() => {
                    this.messageFlag = true;
                }, 1800);
                return
            }
        };
        if(value.length>20){
            messageHint("不能超过20个字！");
            // e.target.value = value.toString(0,3);
            return
        }
        this.setState({
            templateName:value,
        })
    }
    /*点击删除*/
    delTemplate(){
        let  message = "确定要删除吗！";
        this.refs.batchHint.showWindow(true,message,"delete");
    }
    /*删除模板*/
    doDelTemplate(value){

        if(this.delFlag){
            this.delFlag = false;
            let {templateId} = this.state;
            Relay.Store.commitUpdate(
                new DelTemplateByIdMutation({
                    templateId:templateId,
                    enterpriseId:this.enterpriseId,
                    userId:this.userId,
                }),
                {
                    onFailure: () => {

                    },
                    onSuccess: (response) => {
                        let errorCode = response.delTemplateById.delTemplateById.errorCode;
                        if(errorCode==0){
                            let orderTemplates = response.delTemplateById.delTemplateById.orderTemplates;
                            this.setState({
                                orderTemplates:orderTemplates,
                                dataSource_require:this.state.dataSource_require,
                                defaultValue:"请选择模板",
                            },()=>{
                                this.delFlag = true;
                                message.info("删除成功")
                            });
                        }
                    }
                }
            )
        }
    }
    /*备注*/
    remarkinputChange(type,e) {
        let text = e.target.value;
        /*限制？？？*/
        if (text.length > 500)return;
        this.setState({
            remarkinput: text,
            textNum_r: text.length,
        })
    }
    render(){
        let {dataSource_require,orderTemplates,textNum_r} = this.state;
        textNum_r = textNum_r?textNum_r:0;
        orderTemplates = orderTemplates?orderTemplates:[];
        return(
            <div className="order_creat_otherRequ" ref={"templatesList"}>
                <span className="order_creat_otherRequ_title">选择模板：</span>
                <Select
                    key={this.state.defaultValue}
                    value={this.state.defaultValue}
                    showSearch
                    style={{ width: 260 }}
                    placeholder="请选择模板"
                    notFoundContent="请先保存一个模板"
                    optionFilterProp="children"
                    getPopupContainer={()=>this.refs.templatesList}
                    onChange={this.handleChange.bind(this)}
                    className="order_creat_select"
                    dropdownClassName="order_creat_select_drop"
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                    {
                        orderTemplates.map((v,i)=>{
                            return(
                                    <Option key={v.tid} value={v.tid}>{v.name}</Option>
                                )
                        })
                    }
                </Select>
                <span className="order_creat_otherRequ_btn">
                            <Button type="primary" className="order_creat_otherRequ_btn_save" onClick={this.saveTemplate.bind(this)}> 保存页面为模板 </Button>
                            <Button type="primary" className="order_creat_otherRequ_btn_del" onClick={this.delTemplate.bind(this)}> 删除模板 </Button>
                        </span>

                {
                    dataSource_require.map((item,index)=>{
                        return (
                            <OtherRequirementsItem
                                item={item}
                                index={index}
                                key={this.state.defaultValue+index}
                            />
                        )
                    })
                }
                {/*<div style={{width: 1164, height: 180,position:"relative",marginTop:"20px"}}>
                    <span style={{position: "absolute", top: "0px", left: "60px"}}>备&nbsp;&nbsp;注：</span>
                    <InputBox multiline space={"20"}
                              style={{width: 980, height: 174,paddingRight:"60px",borderColor:"#36b3b3"}} ref={'remarkinput'}/>
                </div>*/}
                <div>
                    <span className="order_creat_otherRequ_title2">备注说明：</span>
                    <Input type="textarea" ref={"remarkinput"}
                           className="order_creat_otherRequ_textInput"
                           value={this.state.remarkinput} maxlength="500"
                           placeholder="请填写详细要求"
                           onChange={this.remarkinputChange.bind(this,"remarkinput")}
                    />
                    <span className="order_creat_otherRequ_textNum">{textNum_r}/500</span>
                </div>
                <div style={{minHeight: 0, marginLeft: "16px", marginTop: "20px",overflow:"hidden"}}>
                    <div style={{float: "left"}}>
                        {
                            this.attach()
                        }
                    </div>
                </div>
                <div>
                    <span className="order_creat_otherRequ_title2">附件信息：</span>
                    <span className='create_add_contracts_three' onClick={this.addinstructions.bind(this)}>添加附件</span>
                </div>
                <Modal className="batchhint_modal"
                       title="提示"
                       visible={this.state.saveModalFlag}
                       onCancel={this.handleCancel}
                       onOk={this.onSure.bind(this)}
                >
                    <p className="order_creat_hint_text_left">
                        <span className="order_creat_hint_hint"><i className="red">注：</i>模板不包含备注说明和附件信息的保存!</span>
                        <span className="order_creat_hint_word">模板名称：</span>
                        <Input type="text" ref={"templateName"} className="order_creat_hint_name" value={this.state.templateName} onChange={this.chooseTemplateName.bind(this)} maxLength="20"/>

                    </p>
                </Modal>
                <BatchHint ref={"batchHint"} _doDeleteProduct={this.doDelTemplate.bind(this)}/>
            </div>
        )
    }
}

/*六个要求*/
class OtherRequirementsItem extends React.Component {


    constructor(props) {
        super(props);
        this.state = {
            item: this.props.item,
            othersIds: "",
            textNum: "",
        };
        this.isSave = true;
    }

    componentWillMount() {

    }
    /*点击保存*/
    save(index) {
        let itemSelf = this.state.item;
        let req = /^(\s)*$/g;

        if (req.test(itemSelf.title) || itemSelf.title.length <= 0) {
            message.warning("标题不能为空");
            return
        }

        if (this.isSave) {
            this.isSave = false;
            let itemStr = JSON.stringify(this.state.item);
            let itemPropsStr = JSON.stringify(this.itemProps);

            /*判断是否修改*/
            if (itemStr == itemPropsStr) {
                /*Relay.Store.commitUpdate(
                    new SaveProOthersDetailMutation({
                        pdId: this.pdId,
                        othersDetail: itemStr,
                    }),
                    {
                        onFailure: (err) => {
                            message.error("网络请求失败")
                        },
                        onSuccess: (res) => {
                            let errorCode = res.saveProOthersDetail.responseData.errorCode;
                            if (errorCode == 0) {
                                let proOthersDetailModel = res.saveProOthersDetail.responseData.proOthersDetailModel;
                                this.props._saveItem(index, proOthersDetailModel.othersId);

                                setTimeout(() => {
                                    this.isSave = true;
                                    message.success("保存成功")
                                }, 300)
                            } else {
                                if (errorCode == 500) {
                                    message.error('服务器错误,请联系系统管理员');
                                }
                            }
                        }
                    }
                );*/
            }
        }
    }
    /*内容编辑*/
    handleTextChange(type, index, e) {
        let itemSelf = this.state.item;
        let text = e.target.value;
        /*限制？？？*/
        if (text.length > 500)return;
        this.refs[index + type].value = text;
        itemSelf["content"] = text;
        this.setState({
            item: itemSelf,
            textNum:text.length,
        })
    }

    render() {
        // const {token, previewVisible, previewImage} = this.state;
        let {title, content,type} = this.state.item;
        // let textNum = this.state.textNum?this.state.textNum:0;
        let textNum = content?content.length:0;
        let index = this.props.index;
        return (
            <div className="order_creat_otherReq_item order_creat_otherRequ_edit">
                {/*<p className="order_creat_otherRequ_textp">{title}</p>
                <div className="order_creat_otherRequ_header_text">
                    <Input type="textarea" ref={index + "content"}
                           className="order_creat_otherRequ_textInput"
                           rows={6}
                           value={content} maxlength="500"
                           placeholder="请填写详细要求"
                           onChange={this.handleTextChange.bind(this, "content", index)}
                    />
                </div>*/}
                <span className="order_creat_otherRequ_title2">{title}：</span>
                <Input type="textarea" ref={index + "content"}
                       className="order_creat_otherRequ_textInput"
                       value={content} maxlength="500"
                       placeholder="请填写详细要求"
                       onChange={this.handleTextChange.bind(this, "content", index)}
                />
                <span className="order_creat_otherRequ_textNum">{textNum}/500</span>
            </div>
        )
    }
}